package cn.com.ccxcredit.wallet;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.bitcoinj.core.ECKey;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.crypto.WalletUtils;
import org.web3j.utils.Numeric;

import java.io.File;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Nonnull;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import credit.ccx.com.walletcore.util.MyMnemonicUtils;
import credit.ccx.com.walletcore.util.SecureRandomUtils;
import huixue.cn.com.library.base.SimpleActivity;

import static cn.com.ccxcredit.wallet.R.id;


public class MainActivity extends SimpleActivity {

    @BindView(id.btn_word)
    TextView wordBtn;
    @BindView(id.id_flowlayout)
    TagFlowLayout mFlowlayout;
    LayoutInflater mInflater;
    @BindView(id.tv_gen_private)
    TextView tvGenPrivate;
    @BindView(id.tv_gen_pub)
    TextView tvGenPub;
    @BindView(id.tv_gen_address)
    TextView tvGenAddress;
    @BindView(id.btn_wallet)
    Button btnWallet;

    private String[] mData = null;

    @Override
    public int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        mInflater = getLayoutInflater();
    }

    @Override
    public void addEvent() {

    }


    @OnClick({id.btn_word, id.btn_btc, id.btn_eth,id.btn_wallet})
    public void onViewClicked(View view) {
        if (id.btn_word == view.getId()) {
            //生成助记词
            SecureRandom random = SecureRandomUtils.secureRandom();
            byte[] initialEntropy = new byte[20];
            random.nextBytes(initialEntropy);
            String str = MyMnemonicUtils.generateMnemonic(initialEntropy);
            mData = str.split(" ");

            mFlowlayout.setAdapter(new TagAdapter<String>(mData) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    TextView tv = (TextView) mInflater.inflate(R.layout.tv, mFlowlayout, false);
                    tv.setText(s);
                    return tv;
                }
            });
        } else if (id.btn_btc == view.getId()) {
            //BTC公私钥
            DeterministicSeed deterministicSeed = new DeterministicSeed(Arrays.asList(mData), null, "", 0);

            DeterministicKeyChain deterministicKeyChain = DeterministicKeyChain.builder().seed(deterministicSeed).build();
            BigInteger privKeyBTC = deterministicKeyChain.getKeyByPath(parsePath("M/44'/0'/0'/0/"), true).getPrivKey();

            ECKey ecKey = ECKey.fromPrivate(privKeyBTC);

            String publickey = Numeric.toHexStringNoPrefixZeroPadded(new BigInteger(ecKey.getPubKey()), 66);

            //正式环境应该是主网参数
            String privateKey = ecKey.getPrivateKeyEncoded(MainNetParams.get()).toString();

            tvGenPrivate.setText("私钥：" + privateKey);
            tvGenPub.setText("公钥：" + publickey);

            String address = ecKey.toAddress(MainNetParams.get()).toString();

            tvGenAddress.setText("地址：" + address);

            Log.d("ChannelIndex", "btc:address===" + address);
        } else if (id.btn_eth == view.getId()) {
            DeterministicSeed deterministicSeed = new DeterministicSeed(Arrays.asList(mData), null, "", 0);
            DeterministicKeyChain deterministicKeyChain = DeterministicKeyChain.builder().seed(deterministicSeed).build();
            BigInteger privateKey = deterministicKeyChain.getKeyByPath(parsePath("M/44'/60'/0'/0/"), true).getPrivKey();

            ECKeyPair ecKeyPair = ECKeyPair.create(privateKey);
            String address = Keys.getAddress(ecKeyPair);

            tvGenPrivate.setText("私钥：" + Numeric.toHexStringWithPrefix(ecKeyPair.getPrivateKey()));
            tvGenPub.setText("公钥：" + Numeric.toHexStringWithPrefix(ecKeyPair.getPublicKey()));

            tvGenAddress.setText("地址：" + "Ox"+address);

            Log.d("ChannelIndex", "eth:address===" + address);

        }else if(id.btn_wallet == view.getId()){
            //step 2: 通过BIP39算法生成钱包（助记词、私钥、公钥、地址、keystore文件）
            String keyStoreDir = WalletUtils.getDefaultKeyDirectory();
            System.out.println("生成keyStore文件的默认目录：" + keyStoreDir);
            try{
                String filePath = Environment.getExternalStorageDirectory().toString() + "/Pictures";
                String fileName = WalletUtils.generateNewWalletFile("123456",new File(filePath),false);
                Credentials credentials = WalletUtils.loadCredentials("123456", filePath+"/"+fileName);

                String myAddress = credentials.getAddress();

                Log.d("ChannelIndex", "eth:myAddress===" + myAddress);

            }catch (Exception e){
                e.printStackTrace();;
            }

        }

    }


    public static List<ChildNumber> parsePath(@Nonnull String path) {
        String[] parsedNodes = path.replace("M", "").split("/");
        List<ChildNumber> nodes = new ArrayList<ChildNumber>();

        for (String n : parsedNodes) {
            n = n.replaceAll(" ", "");
            if (n.length() == 0) continue;
            boolean isHard = n.endsWith("'");
            if (isHard) n = n.substring(0, n.length() - 1);
            int nodeNumber = Integer.parseInt(n);
            nodes.add(new ChildNumber(nodeNumber, isHard));
        }

        return nodes;
    }



}
